package pixivhelper.bravedefault.com;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import okhttp3.*;

import java.io.IOException;

public class Authorize {
    public static String clientId = "KzEZED7aC0vird8jWyHM38mXjNTY";
    public static String clientSecret = "W9JZoJe00qPvJsiyCGT3CCtC6ZUtdpKpzMbNlUGP";

    public interface AuthorizeCallback {
        void onFailure(Authorize authorize, Exception exception);
        void onResponse(Authorize authorize, Oauth oauth);
        boolean onSaveAuthorize(Authorize authorize, Oauth oauth) throws Exception;
    }

    public static Headers defaultHeaders() {
        Headers headers = new Headers.Builder()
                .add("User-Agent", "PixivIOSApp/7.1.8 (iOS 11.3; iPhone9,2)")
                .add("App-OS-Version", "11.3")
                .add("App-Version", "7.1.8")
                .add("App-OS", "ios")
                .build();
        return headers;
    }

    private OkHttpClient client;

    public Authorize(OkHttpClient client) {
        this.client = client;
    }

    public Authorize() {
        this.client = PixivHelper.client();
    }

    public Call authorize(String username, String password, AuthorizeCallback callback) {
        String url = "https://"+Hostname.oauth_secure_pixiv_net.getRawValue() + "/auth/token";
        RequestBody requestBody = new FormBody.Builder()
                .add("grant_type", "password")
                .add("client_id", Authorize.clientId)
                .add("client_secret", Authorize.clientSecret)
                .add("username", username.trim())
                .add("password", password.trim())
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .headers(Authorize.defaultHeaders())
                .build();

        Call call =  client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                callback.onFailure(Authorize.this, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    System.out.println(result);
                    GsonBuilder builder = new GsonBuilder();
                    Oauth.OauthAdapter adapter = new Oauth.OauthAdapter();
                    builder.registerTypeAdapter(Oauth.class, adapter);
                    Gson gson = builder.create();
                    Oauth oauth = gson.fromJson(result, Oauth.class);
                    try {
                        if (callback.onSaveAuthorize(Authorize.this, oauth)) {
                            callback.onResponse(Authorize.this, oauth);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        callback.onFailure(Authorize.this, e);
                    }

                }else {
                    callback.onFailure(Authorize.this, new Exception(response.message()));
                }
            }
        });
        return call;
    }
}
